/**
 * 
 */
package com.base.myproject.client.busi.b2c.shopping;

import java.util.ArrayList;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseStoreEvent;
import com.base.myproject.client.busi.BaseStoreListener;
import com.base.myproject.client.busi.BaseStoreEvent.EventType;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.system.SystemMessage;
import com.base.myproject.client.tools.SendServlet;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseImageList;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

/**
 * 显示购物车
 * 
 * @author zgw 2009-7-29 下午02:01:44 javazgw@gmail.com
 */
public class ShoppingCarPanel extends LayoutContainer {
	String ccode = null;
	BasePagingLoader loder;
	GroupingStore<BaseModelData> groupstore = null;
	static BaseStore<BaseModelData> store = null;
	static FormBinding formbinding = null;
	static BaseImageList bl = null;
	static java.util.LinkedList<ShopCartObject> ll = new java.util.LinkedList<ShopCartObject>();
	static double subtotal = 0; //购物车合计数
	static double jiesheng = 0; //节省金额

	public ShoppingCarPanel(String ccode) {
		this.ccode = ccode;
		init();
	}

	public void init() {
		// getgroupstore();
		createscript();
		submit();
		CreateImageStore();
//		Widget w = CreateForm();
		add(CreateShoppingCarX());
//		add(w);
	}

	@Deprecated
	Grid CreateShoppingCar() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();

		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		ColumnConfig subject = new ColumnConfig("b2cgcode", "代码", 100);
		columns.add(subject);

		ColumnConfig bcode = new ColumnConfig("b2cgname", "商品名", 100);
		columns.add(bcode);
		ColumnConfig qty = new ColumnConfig("qty", "商品数量", 100);
		// TextField<String> qtytext = new TextField<String>();
		// qty.setEditor(new CellEditor(qtytext));
		columns.add(qty);
		ColumnConfig price = new ColumnConfig("price", "单价", 100);
		columns.add(price);
		ColumnConfig discountprice = new ColumnConfig("discountprice", "折扣后单价",
				100);
		columns.add(discountprice);
		ColumnConfig totle = new ColumnConfig("totle", "合计", 100);
		columns.add(totle);

		ColumnConfig shopdate = new ColumnConfig("shopdate", "购买日期", 100);
		columns.add(shopdate);

		final ColumnModel cm = new ColumnModel(columns);
		// BaseGroupingView view = new BaseGroupingView();
		GroupingView view = new GroupingView();
		// view.setShowGroupedColumn(false);
		// view.setForceFit(true);
		// view.setGroupRenderer(new GridGroupRenderer() {
		// public String render(GroupColumnData data) {
		// // String f = cm.getColumnById(data.field).getHeader();
		// // String l = data.models.size() == 1 ? "Item" : "Items";
		// //return f + ": " + data.group + " (" + data.models.size() + " " + l
		// + ")";
		// return "z";
		// }
		// });

		EditorGrid<BaseModelData> grid = new EditorGrid<BaseModelData>(
				groupstore, cm);
		grid.setSelectionModel(cbs);
		// grid.mask("eeee");
		grid.setView(view);
		grid.setBorders(true);
		grid.setHeight(400);
		grid.setWidth(800);
		grid.getSelectionModel().addSelectionChangedListener(
				new SelectionChangedListener<BaseModelData>() {

					@Override
					public void selectionChanged(
							SelectionChangedEvent<BaseModelData> se) {
						// System.out.println(se.getSelection().size());
						// System.out.println(se.getSelection().get(0).getPropertyNames().size());

						if (se.getSelection().size() > 0) {
							System.out.println(se.getSelectedItem().get(
									"b2cgcode"));
							formbinding.bind(se.getSelectedItem());
						} else {
							formbinding.unbind();
						}
					}

				});
		return grid;
	}

	static Widget CreateShoppingCarX() {

		bl = new BaseImageList(store, null, false) {

			protected native String getTemplate() /*-{
		var r3= ['<form id=\"formshoppingcart\"  action=\"/"+GWT.getModuleName()+"/BaseServlet?action=test1\" method=\"post\"><table class=\"tblCart\"   border=\"0\" width=\"100%\" cellspacing=\"1px\" cellpadding=\"1px\" id=\"cartContentsDisplay\"> ', 

			 '<tr class="tableHeading"> ',
		'<th   scope="col" id="imagepath">商品</th> ',
		'<th   scope="col" id="b2cgname">商品名</th> ',
		'<th   scope="col" id="finalprice">单价</th> ',
		
		'<th   scope="col" id="qty">数量</th> ',
		
	
		'<th   scope="col" id="index">删除</th> ',
		'<th   scope="col" id="totle">总价</th> ',

		'<tpl  for=".">',
		'<tpl if="xindex %2 ==1">',
		'<tr class="tblEven" id=\"{icode}\">',
		'</tpl>',
		'<tpl if="xindex %2 ==0">',
		'<tr class="tblOdd" id=\"{icode}\">',
		'</tpl>',
		
		'<td width=\"25%\" ><img src =\"{imagepath}\" width=\"100px\"  /></td>',
		'<td width=\"25%\" style=\"text-align:left" >{b2cgname}</td>',
		'<td width=\"10%\">{finalprice}</td>',
		
		'<td width=\"10%\"><input name=\"{icode}ss\" type=\"text\" onKeyUp=\"javascript:setautodisplaytocenter(this.value,{icode})\" /></td>',
		
	
		'<td width=\"10%\"><a href=\"javascript:void(0);\" onclick=\"javascript:doDeltr(this);\">删除</a></td>',
		'<td width=\"10%\">{totle}</td>',
		'</tpl>',


		'</tr>',

		'</table><hr /><div id="shopcarsubtotal" style="float:right">总金额:</div><div  style="float:center"><a href=\"javascript:void(0)\"  onclick=\"javascript:shoppingcartsubmit(formshoppingcart)\" style="background-color:#FF6600; color:#FFFFFF">下订单 </a> ',
		'<a href=\"javascript:void(0)\"  onclick=\"javascript:continueshopping()\" style="background-color:#999999; color:#FFFFFF">    继续购物</a></div>',
	
		'</form>',
		'<div class="x-clear"><hr /></div>'].join(""); 
		return r3;
	}-*/;

		};
		return bl;
	}

	private native void createscript()/*-{
			$wnd.continueshopping = function(){
			@com.base.myproject.client.busi.b2c.shopping.ShoppingCarPanel::aaa()();
		}
		$wnd.setautodisplaytocenter = function(qty,icode){
			var iicode = ""+icode+"";
			var pric = $wnd.$("#"+iicode+" td").eq(2).html();
		
			var totalnumber = new Number(pric*qty);
	
			$wnd.$("#"+iicode+" td").eq(5).html((totalnumber.toFixed(2))+"");
	

			@com.base.myproject.client.busi.b2c.shopping.ShoppingCarPanel::setQty(Ljava/lang/String;Ljava/lang/String;)(""+qty+"",""+icode+"");
		var subtotal = @com.base.myproject.client.busi.b2c.shopping.ShoppingCarPanel::subtotal;
		var subtotalnumber = new Number(subtotal);
		$wnd.$("#shopcarsubtotal").html("总金额:"+subtotalnumber.toFixed(2)+"");
		};
	
	}-*/;

	private native void submit()/*-{
		$wnd.shoppingcartsubmit = function(formid){
			
			
//		var str = $("form123").serialize();
//			alert(str);
//		formid.submit();
		@com.base.myproject.client.busi.b2c.shopping.ShoppingCarPanel::submitform()();
		

		}
	}-*/;

	private static void aaa()
	{
		System.out.println("1");
		//com.base.myproject.client.busi.b2c.MainPage.getMainpage().aaa();
		System.out.println("2");
	}
	
	private static void submitform()
	{
		for (ShopCartObject sco : ll) {
			
			if(sco.getQty()==null || sco.getQty().equals("") ||sco.getQty().equals("0"))
			{
				
				MessageBox.alert("警告", "有商品的数量没有录入或者录入错误。", null);
				return;
			}
		}
		
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
		.create(com.base.myproject.client.tools.GreetingService.class);

//System.out.println(ll.size());
greetingService.greetServerShoppingCart(ll,Env.getCcode(),
		new AsyncCallback<String>() {
			public void onFailure(Throwable caught) {
				// Show the RPC error message to the user
				System.out.println("error");
			}

			public void onSuccess(String result) {
				System.out.println(result);
			}
		});
	}
	@SuppressWarnings("unused")
	private static void setQty(String qty, String icode) {
		//System.out.println("0000"+qty+"s");
		
		//System.out.println(ll.size()+" size");
		/*
		 * for(int i=0;i<store.getCount();i++) { if(store.getValue(i,
		 * "icode").equals(icode)) { System.out.println("equals"); } else {
		 * //System.out.println("unequals"); } }
		 */

		if(!Tools.isNumeric(qty))
		{
//			Info.display("错误", "请录入正确的格式。");
			qty = "0";
		}
		subtotal = 0;
		
		for (ShopCartObject sco : ll) {
			if (sco.getIcode().equals(icode)) {
				
				String price = sco.getPrice();
				String finalprice = sco.getFinalprice();
				if(!Tools.isNumeric(price))
				{
					price = "0";
//					return;
				}
				sco.setQty(qty);
				double totle = Integer.parseInt(qty) * Double.parseDouble(finalprice);
//				if(Tools.isDigit(finalprice))
//				{
//					totle = Integer.parseInt(qty) * Integer.parseInt(finalprice);
//				}
				
			//	System.out.println(sco.getTotle());
//				BigDecimal b = new BigDecimal(totle);
//				totle = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//				totle =java.lang.Math.;
				sco.setTotle(totle+"");
//				System.out.println(sco.getTotle());
				
			}
			if(Tools.isNumeric(sco.getTotle()))
			subtotal = subtotal+Double.parseDouble(sco.getTotle());
			
			
		}
		
		setSubtotal(subtotal);


	}

	/**
	 * @return the subtotal
	 */
	public static double getSubtotal() {
		return subtotal;
	}

	/**
	 * @param subtotal the subtotal to set
	 */
	public static void setSubtotal(double subtotal) {
		ShoppingCarPanel.subtotal = subtotal;
	}

	/**
	 * @return the jiesheng
	 */
	public static double getJiesheng() {
		return jiesheng;
	}

	/**
	 * @param jiesheng the jiesheng to set
	 */
	public static void setJiesheng(int jiesheng) {
		ShoppingCarPanel.jiesheng = jiesheng;
	}

	private void getgroupstore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.addField("icode");
		type.addField("b2cgcode");
		type.addField("b2cgname");
		type.addField("gcode");
		type.addField("gname");
		type.addField("shopdate");
		type.addField("qty");
		type.addField("price");
		type.addField("totle");
		type.addField("discountprice");
		type.addField("bcode");
		type.addField("bname");

		StoreInfo info = new StoreInfo();

		info.setTablename("b2cshopcar");
		info.setSql("select * from b2cshopcar where ccode = '" + ccode + "'");
		SendServlet ss = new SendServlet();
		loder = ss.getBaseLoader(type, info);
		groupstore = new GroupingStore<BaseModelData>(loder);
		// groupstore = new BaseGroupingStore<JDBCModelData>(loder);

		loder.load();
		groupstore.groupBy("shopdate");

		// loder.addLoadListener(new LoadListener(){
		// public void loaderLoad(LoadEvent e){
		//				
		// }
		// });
		// groupstore.addStoreListener(new StoreListener<JDBCModelData>(){});

	}

	/*
	 * public boolean isNumeric(String str) { Pattern pattern =
	 * Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if(
	 * !isNum.matches() ) { return false; } return true; }
	 */
	public Widget CreateForm() {
		final FormPanel bfp = new FormPanel();

		TextField<String> icode = new TextField<String>();
		icode.setName("icode");
		icode.setAllowBlank(false);
		icode.setFieldLabel("编码");
		bfp.add(icode);

		TextField<String> b2cgcode = new TextField<String>();
		b2cgcode.setName("b2cgcode");
		b2cgcode.setAllowBlank(false);
		b2cgcode.setFieldLabel("商品编码");
		b2cgcode.setEnabled(false);
		bfp.add(b2cgcode);
		TextField<String> b2cgname = new TextField<String>();
		b2cgname.setName("b2cgname");
		b2cgname.setAllowBlank(false);
		b2cgname.setFieldLabel("商品名称");
		b2cgname.setEnabled(false);
		bfp.add(b2cgname);
		final NumberField qty = new NumberField();
		qty.setName("qty");
		qty.setAllowBlank(false);
		qty.setFieldLabel("数量");
		bfp.add(qty);

		Button save = new Button("保存");
		bfp.addButton(save);
		save.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				// System.out.println(formbinding.getModel().get("qty"));
				// System.out.println(groupstore.getAt(groupstore.indexOf((BaseModelData)formbinding.getModel())).get("qty"));
				// groupstore.rejectChanges();
				String icode = formbinding.getModel().get("icode");

				groupstore.getRecord((BaseModelData) formbinding.getModel())
						.set("qty", qty.getValue());

				String sql = "update b2cshopcar set qty='" + qty.getValue()
						+ "' where icode='" + icode + "'";
				System.out.println(sql);
				if (qty.getValue() == null || qty.getValue().equals("null")) {
					Info.display("", SystemMessage.getMessage(4, 2));
					return;
				}

				SendServlet ss = new SendServlet();
				try {
					ss.sendServlet("BaseServlet", "sql=" + sql + "&Action="
							+ SystemMessage.getMessage(2, 0),
							new RequestCallback() {

								@Override
								public void onError(Request request,
										Throwable exception) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onResponseReceived(Request request,
										Response response) {

									System.out.println(response.getText());
									Document doc = XMLParser
											.parse((String) response.getText());
									NodeList list = doc
											.getElementsByTagName("root");
									Node node = list.item(0);
									Element elem = (Element) node;

									if (elem.getAttribute("status").equals(
											SystemMessage.getMessage(1, 0))) {
										// MessageBox.info("", "注册成功", null);
										Info.display("", SystemMessage
												.getMessage(4, 0));
									} else {
										Info.display("", SystemMessage
												.getMessage(4, 1));
									}
								}

							});
				} catch (RequestException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});
		Button delete = new Button("删除");

		delete.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				// System.out.println(formbinding.getModel().get("qty"));
				// System.out.println(groupstore.getAt(groupstore.indexOf((BaseModelData)formbinding.getModel())).get("qty"));
				// groupstore.rejectChanges();
				String icode = formbinding.getModel().get("icode");

				// groupstore.getRecord((BaseModelData)formbinding.getModel()).set("qty",qty.getValue());
				groupstore.remove((BaseModelData) formbinding.getModel());
				String sql = "delete  b2cshopcar where   icode='" + icode + "'";
				System.out.println(sql);
				if (icode == null || icode.equals("null")) {
					Info.display("", SystemMessage.getMessage(4, 5));
					return;
				}
				SendServlet ss = new SendServlet();
				try {
					ss.sendServlet("BaseServlet", "sql=" + sql + "&Action="
							+ SystemMessage.getMessage(2, 1),
							new RequestCallback() {

								@Override
								public void onError(Request request,
										Throwable exception) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onResponseReceived(Request request,
										Response response) {

									System.out.println(response.getText());
									Document doc = XMLParser
											.parse((String) response.getText());
									NodeList list = doc
											.getElementsByTagName("root");
									Node node = list.item(0);
									Element elem = (Element) node;

									if (elem.getAttribute("status").equals(
											SystemMessage.getMessage(1, 0))) {
										// MessageBox.info("", "注册成功", null);
										Info.display("", SystemMessage
												.getMessage(4, 3));
									} else {
										Info.display("", SystemMessage
												.getMessage(4, 4));
									}
								}

							});
				} catch (RequestException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
		bfp.addButton(delete);
		formbinding = new FormBinding(bfp, true);

		return bfp;
	}

	void CreateImageStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.addField("icode");
		type.addField("b2cgcode");
		type.addField("b2cgname");
		type.addField("gcode");
		type.addField("gname");
		type.addField("shopdate");
		type.addField("qty");
		type.addField("price");
		type.addField("totle");
		type.addField("discountprice");
		type.addField("bcode");
		type.addField("bname");
		type.addField("imagepath");
		type.addField("finalprice");

		StoreInfo info = new StoreInfo();

		info.setTablename("b2cshopcar");
		info.setSql("select   case  when discountprice is null then price when discountprice ='' then price when cast(discountprice  as money)< cast(price as money) then discountprice when cast(discountprice  as money)>= cast(price as money)  then price  end as finalprice, *  from b2cshopcar  where ccode = '" + ccode + "'");

		store = new BaseStore<BaseModelData>(type, info);
		store.addBaseStoreListener(EventType.LOAD_COMPLETE,
				new BaseStoreListener() {

					@Override
					public void BaseStoreEventHandle(BaseStoreEvent evt) {
						ll.clear();
						for (int i = 0; i < store.getCount(); i++) {
							ShopCartObject sco = new ShopCartObject();

							Object icode = store.getValue(i, "icode");
							Object b2cgcode = store.getValue(i, "b2cgcode");
							Object b2cgname = store.getValue(i, "b2cgname");
							Object gcode = store.getValue(i, "gcode");
							Object gname = store.getValue(i, "gname");
							Object shopdate = store.getValue(i, "shopdate");
							Object qty = store.getValue(i, "qty");
							Object price = store.getValue(i, "price");
							Object totle = store.getValue(i, "totle");
							Object discountprice = store.getValue(i,
									"discountprice");
							Object bcode = store.getValue(i, "bcode");
							Object bname = store.getValue(i, "bname");
							Object finalprice = store.getValue(i, "finalprice");
							sco.setB2cgcode(b2cgcode==null?"":b2cgcode.toString());
							sco.setB2cgname(b2cgname==null?"":b2cgname.toString());
							sco.setBcode(bcode==null?"":bcode.toString());
							sco.setBname(bname==null?"":bname.toString());
							sco.setDiscountprice(discountprice==null?"":discountprice.toString());
							sco.setGcode(gcode==null?"":gcode.toString());
							sco.setGname(gname==null?"":gname.toString());
							sco.setIcode(icode==null?"":icode.toString());
							sco.setPrice(price==null?"":price.toString());
							sco.setQty(qty==null?"":qty.toString());
							sco.setShopdate(shopdate==null?"":shopdate.toString());
							sco.setTotle(totle==null?"":totle.toString());
							sco.setFinalprice(finalprice==null?"":finalprice.toString());
							ll.add(sco);
						}
					}

					@Override
					public void onBrowserEvent(Event event) {

					}

				});

	}

}
